Search code examples
typescriptwebpackractivejs

Using ractive.js with webpack - "require is not defined"


I'm trying to create a single page app using ractive.js and typescript, bundled by webpack, however the browser says require is not defined.

I have been through so many tutorials my head is swimming, but I think this should work.

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {  
    target: 'web',
    mode: 'development',
    entry: './src/main.ts',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'build.js'
      },
      resolve: {
        extensions: [".ts", ".tsx", ".js"]
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {

                }
            },
            { 
                test: /\.html$/,
                loader: 'ractive'
            }
        ]
    }
};

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./built/",
        "sourceMap": true,
        "strict": true,
        "noImplicitReturns": true,
        "module": "es2015",
        "moduleResolution": "node",
        "target": "es5"
    },
    "include": [
        "./src/**/*"
    ]
}

index.html

<!DOCTYPE html>  
<html>  
    <head>
        <meta charset="UTF-8">
        <title>Test</title>
    </head>

    <body>
        <div id="app"></div>

        <script src="dist/build.js"></script>
    </body>
</html>  

main.ts

import Ractive from 'ractive';

let App = new Ractive({  
  el: '#app',
  template: '<input type="text" value="{{name}}"><p>Hello {{name}}</p>',
  data: {
    name: 'World'
  }
});

export default App;  

Stackoverflow won't let me submit this without more details. I'm not sure what more I can add and I feel posting my configs is the best explanation of the issue.


Solution

  • The param in tsconfig shouldn't be there, please delete it:

    "moduleResolution": "node"
    

    Also change value of prop module to

    "module": "commonjs"
    

    Further reading: